<template>
    <div class="login-container">
        <el-card class="login-card">
            <el-row>
                <el-col :span="12" class="image-col">
                    <img :src="imageSrc" alt="  " />
                </el-col>
                <el-col :span="12">
                    <el-box class="input-box">
                        <h2 class="title">邮箱登录</h2>
                        <el-form :model="loginForm" :rules="rules" ref="loginFormRef" label-width="80px">
                            <el-form-item label="邮箱" prop="email">
                                <el-input v-model="loginForm.email" placeholder="请输入邮箱"
                                    @input="handleInput('email', $event)"></el-input>
                            </el-form-item>

                            <el-form-item label="密码" prop="password">
                                <el-input v-model="loginForm.password" type="password" placeholder="请输入密码"
                                    @input="handleInput('password', $event)"></el-input>
                            </el-form-item>

                            <el-form-item label="验证码" prop="verifyCode">
                                <el-input v-model="loginForm.verifyCode" placeholder="请输入验证码"
                                    @input="handleInput('verifyCode', $event)">
                                    <template #append>
                                        <el-button
                                            :style="{ backgroundColor: isSending || countdown > 0 ? '#ccc' : '#4CAF50', color: 'white' }"
                                            @click="sendVerifyCode" :disabled="isSending || countdown > 0">
                                            {{ countdown > 0 ? `${countdown}秒` : '获取验证码' }}
                                        </el-button>
                                    </template>
                                </el-input>
                            </el-form-item>

                            <el-form-item>
                                <el-checkbox v-model="rememberPassword">记住密码</el-checkbox>
                            </el-form-item>

                            <el-row :gutter="25">
                                <el-col :span="12">
                                    <el-button class="btn" type="primary" @click="onSubmit">登录</el-button>
                                </el-col>
                            </el-row>

                            <el-form-item class="footer-links">
                                <el-col>
                                    <span @click="goToRegister" class="link">没有账号？立即注册</span>
                                    <span class="separator">|</span>
                                    <span @click="goToForgotPassword" class="link">忘记密码？</span>
                                </el-col>
                            </el-form-item>

                        </el-form>
                    </el-box>
                </el-col>
            </el-row>
        </el-card>
    </div>
</template>

<script>
import { useRouter } from 'vue-router';
import { reactive, ref } from 'vue';
import { md5 } from 'js-md5';
import image1 from '@/assets/Login.jpg'; // 确保路径正确
import { ElMessage, ElNotification } from 'element-plus';

export default {
    name: 'LoginPage',
    setup() {
        const loginForm = reactive({
            email: '',
            password: '',
            verifyCode: ''
        });

        const loginFormRef = ref(null);
        const imageSrc = ref(image1);

        const rules = {
            email: [
                { required: true, message: '请输入邮箱', trigger: 'blur' },
                { type: 'email', message: '邮箱格式不正确', trigger: 'blur' }
            ],
            password: [
                { required: true, message: '请输入密码', trigger: 'blur' }
            ],
            verifyCode: [
                { required: true, message: '请输入验证码', trigger: 'blur' }
            ]
        };

        const rememberPassword = ref(false);
        const loading = ref(false);
        const countdown = ref(0);
        const isSending = ref(false);
        const verificationCode = ref(0);
        const router = useRouter(); // 使用 useRouter 获取路由实例

        const sendVerifyCode = async () => {
            if (isSending.value || countdown.value > 0 || loginForm.email == '') return;
            isSending.value = true;
            let url = 'http://localhost:8080/api/user/sendLoginEmailVerificationCode?email=';
            url += loginForm.email;
            console.log(url);
            // 发送验证码
            fetch(url, {
                method: 'POST',
                headers: {
                    'Content-Type': 'text/plain',
                    'Accept': 'application/json',
                },
                body: loginForm.email
            }).then(response => {
                if (!response.ok) {
                    throw new Error(`HTTP error! Status: ${response.status}`);
                }
                return response.json();
            }).then(data => {
                if (data['code'] == 200) {
                    verificationCode.value = data['msg'];
                    console.log(data['msg']);
                    console.log('验证码发送成功'); // Debug log

                    countdown.value = 60; // 开始倒计时
                    const timer = setInterval(() => {
                        if (countdown.value > 0) {
                            countdown.value--;
                        } else {
                            clearInterval(timer);
                            isSending.value = false; // 结束发送状态
                            verificationCode.value = '';
                            console.log('倒计时结束，按钮恢复'); // Debug log
                        }
                    }, 1000);
                }
                else {
                    ElNotification({
                        title: 'Error',
                        message: '用户不存在',
                        type: 'error',
                    })
                    isSending.value = false;
                }
            }).catch(error => console.error('Error:', error));
        };

        const handleInput = (field, event) => {
            const value = event.target.value;

            switch (field) {
                case 'email':
                    loginForm.email = value;
                    validateField('email');
                    break;
                case 'password':
                    loginForm.password = value;
                    validateField('password');
                    break;
                case 'verifyCode':
                    loginForm.verifyCode = value;
                    validateField('verifyCode');
                    break;
            }
        };

        const validateField = (field) => {
            if (loginFormRef.value) {
                loginFormRef.value.validateField(field);
            }
        };

        const onSubmit = () => {
            loading.value = true;
            // 验证码错误
            // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
            if (verificationCode.value != loginForm.verifyCode) {
                ElMessage.error('验证码错误')
                return;
            }
            // 登录
            fetch('http://localhost:8080/api/user/login', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Accept': 'application/json',
                },
                body: JSON.stringify({
                    email: loginForm.email,
                    password: md5(loginForm.password),
                })
            }).then(response => {
                if (!response.ok) {
                    throw new Error(`HTTP error! Status: ${response.status}`)
                }
                return response.json()
            }).then(data => {
                if (data['code'] != 200) {
                    ElNotification({
                        title: 'Error',
                        message: data['msg'],
                        type: 'error',
                    })
                }
                else if (data['code'] == 200) {
                    localStorage.setItem('tokenName', data['data']['tokenName']);
                    localStorage.setItem('tokenValue', data['data']['tokenValue']);
                    console.log(localStorage.getItem('tokenName') + '\n' + localStorage.getItem('tokenValue'))
                    ElMessage({
                        message: '登录成功',
                        type: 'success'
                    })
                    if (router) {
                        router.push('/home');
                    } else {
                        console.error("Router is undefined")
                    }
                    loading.value = false;
                }
            }).catch(error => console.error('Error: ', error));
        };

        const goToRegister = () => {
            if (router) {
                router.push('/register'); // 跳转到注册页面
            } else {
                console.error("Router is undefined");
            }
        };

        const goToForgotPassword = () => {
            if (router) {
                router.push('/reset_email'); // 跳转到忘记页面
            } else {
                console.error("Router is undefined");
            }
        };


        return {
            loginForm,
            rules,
            rememberPassword,
            loading,
            onSubmit,
            sendVerifyCode,
            handleInput,
            loginFormRef,
            imageSrc,
            countdown,
            isSending,
            goToRegister,
            goToForgotPassword
        };
    }
}
</script>

<style scoped>
.title {
    text-align: center;
}

.login-container {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100vh;
    background-color: #f6f4ef;
    margin: auto;
}

.login-card {
    height: auto;
    width: auto;
    border-radius: 25px;
}

.image-col {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    flex-grow: 1;
}

.input-box {
    display: flex;
    flex-direction: column;
    justify-content: center;
    flex-grow: 1;
    margin-top: 50px;
}

img {
    width: auto;
    height: auto;
    object-fit: cover;
}

.btn {
    height: 120%;
    width: 220%;
    border-radius: 10px;
}

.footer-links {
    text-align: center;
}

.link {
    cursor: pointer;
    color: #409EFF;
}

.separator {
    margin: 0 10px;
}

.btn1 {
    color: #597fa5;
}
</style>